package com.echo.boot.structure.linearlist.list;

/**
 * Created with IntelliJ IDEA
 * Created By CQ
 * Date: 2020/5/1
 * Time: 17:37
 * 抽象类实现公共的方法，抽象类可以不实现接口的方法
 */
public abstract class MyAbstractList<E> implements MyList<E> {
    protected int size;

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean contains(E element) {
        return indexOf(element) != ELEMENT_NOT_FOUND;
    }

    @Override
    public void add(E element) {
//        elements[size++] = element;
        // size = 0;
        add(size, element);
    }

    // 边界检查
    protected void rangeCheck(int index) {
        if (index < 0 || index >= size) {
            outOfBounds(index);
        }
    }

    protected void rangeCheckForAdd(int index) {
        if (index < 0 || index > size) {
            outOfBounds(index);
        }
    }

    protected void outOfBounds(int index) {
        throw new IndexOutOfBoundsException("index : " + index + ", size : " + size);
    }
}
